package com.menker.app.util;

import android.app.Activity;
import android.app.Dialog;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Gravity;

import com.flyco.animation.BaseAnimatorSet;
import com.flyco.animation.FadeEnter.FadeEnter;
import com.flyco.animation.FadeExit.FadeExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.menker.app.R;
import com.menker.app.common.SharedPreferencesHelper;
import com.menker.app.common.Utils;

import java.io.File;

import myandroid.library.util.ApplicationHelper;

/**
 * @author J.Huang
 *
 */

public class DialogUtils {
    private static Dialog mProgressDialog;

    private static NormalDialog sDialog;

    public static void showUpdateDialog(final Activity activity, final String url, final SharedPreferencesHelper sharedPrefHelper, boolean forceUpdate) {
        if (activity == null || TextUtils.isEmpty(url)) {
            return;
        }
        BaseAnimatorSet bas_in = new FadeEnter();
        BaseAnimatorSet bas_out = new FadeExit();

        String title = "当前已有新的版本，请更新应用";

        if (sDialog != null && sDialog.isShowing()) {
            return;
        }

        OnBtnClickL downloadBtnClickL = new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                dismissCustomDialog();

                showProgressDialog(activity, "下载更新包中…");

                // 删除原有安装包
                File file = new File(
                        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                                + File.separator + activity.getResources().getString(R.string.app_name)+ ".apk");
                if(file.exists()) {
                    file.delete();
                }

                // 调用系统下载
                DownloadManager dm = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
                DownloadManager.Request request = new DownloadManager.Request(
                        Uri.parse(url));
                request.setMimeType("application/vnd.android.package-archive");
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                        activity.getResources().getString(R.string.app_name)+ ".apk");
                // 设置为可被媒体扫描器找到
                request.allowScanningByMediaScanner();
                // 设置为可见和可管理

                request.setVisibleInDownloadsUi(true);
                long reference = dm.enqueue(request);
                sharedPrefHelper.setData("downloadApkRef", reference);
            }
        };

        sDialog = new NormalDialog(activity);

        sDialog.isTitleShow(false)
                .bgColor(Color.parseColor("#FFFFFF"))
                .cornerRadius(5)
                .content(title)
                .contentGravity(Gravity.CENTER)
                .contentTextColor(Color.parseColor("#333333"))
                .dividerColor(Color.parseColor("#CCCCCC"))
                .widthScale(0.7f)
                .showAnim(bas_in)
                .dismissAnim(bas_out);

        // 强制性更新, 不可关闭该窗口
        if (forceUpdate) {
            sDialog
                    .btnNum(1)
                    .btnText("下载更新")
                    .btnTextSize(15.5f)
                    .btnTextColor(Color.parseColor("#0092FF"));

            sDialog.setCanceledOnTouchOutside(false);
            sDialog.setCancelable(false);

            sDialog.setOnBtnClickL(
                    downloadBtnClickL
            );
        } else {
            sDialog
                    .btnNum(2)
                    .btnText("以后再说", "下载更新")
                    .btnTextSize(15.5f, 15.5f)
                    .btnTextColor(Color.parseColor("#333333"), Color.parseColor("#0092FF"));

            sDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    dismissCustomDialog();
                }
            });
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                sDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        dismissCustomDialog();
                    }
                });
            }

            sDialog.setOnBtnClickL(
                    new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            dismissCustomDialog();
                        }
                    },
                    downloadBtnClickL
            );
        }

        sDialog.show();
    }

    public static void showAlreadyNewestVersionDialog(final Activity activity) {
        if (activity == null) {
            return;
        }
        BaseAnimatorSet bas_in = new FadeEnter();
        BaseAnimatorSet bas_out = new FadeExit();

        String content = "当前已是最新版本\n版本号：" + Utils.App.getAppVersionName();

        if (sDialog != null && sDialog.isShowing()) {
            return;
        }

        sDialog = new NormalDialog(activity);

        sDialog.isTitleShow(false)
                .bgColor(Color.parseColor("#FFFFFF"))
                .cornerRadius(5)
                .content(content)
                .contentGravity(Gravity.CENTER)
                .contentTextColor(Color.parseColor("#333333"))
                .dividerColor(Color.parseColor("#CCCCCC"))
                .widthScale(0.7f)
                .showAnim(bas_in)
                .dismissAnim(bas_out)
                .btnNum(1)
                .btnText("确定")
                .btnTextSize(15.5f)
                .btnTextColor(Color.parseColor("#0092FF"));

        sDialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dismissCustomDialog();
                    }});

        sDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                dismissCustomDialog();
            }
        });

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            sDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    dismissCustomDialog();
                }
            });
        }

        sDialog.show();
    }

    /**
     * 显示加载进度
     * @param activity
     * @param msg
     */
    private static void showProgressDialog(Activity activity, String msg) {
        try {
            if (activity == null) {
                return;
            }
            if (mProgressDialog != null && mProgressDialog.isShowing()) {
                return;
            }

            ProgressDialog dialog = ProgressDialog.show(activity, "", msg);
            dialog.setCanceledOnTouchOutside(false);
            dialog.setCancelable(false);

            mProgressDialog = dialog;
            mProgressDialog.show();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void showRequestBasicPermissionsDialog(final Activity activity, OnBtnClickL onBtnClickLRequestPermissions) {
        if (activity == null) {
            return;
        }
        BaseAnimatorSet bas_in = new FadeEnter();
        BaseAnimatorSet bas_out = new FadeExit();

        String title = "\t\"" + activity.getString(R.string.app_name) + "\"想获取您的移动设备状态:";
        String content = "\"状态\"包括联网方式、设备ID、SD存储卡等。这些可在\"设置\"中配置。";

        if (sDialog != null && sDialog.isShowing()) {
            return;
        }

        sDialog = new NormalDialog(activity);

        sDialog.isTitleShow(true)
                .title(title)
                .titleTextColor(Color.parseColor("#000000"))
                .titleTextSize(16)
                .btnNum(2)
                .style(NormalDialog.STYLE_TWO)
                .cornerRadius(5)
                .content(content)
                .contentGravity(Gravity.CENTER)
                .contentTextSize(13)
                .contentTextColor(Color.parseColor("#333333"))
                .dividerColor(Color.parseColor("#CCCCCC"))
                .btnText("不允许", "允许")
                .btnTextSize(15.5f, 15.5f)
                .btnTextColor(Color.parseColor("#333333"), Color.parseColor("#41ACFD"))
                .widthScale(0.8f)
                .showAnim(bas_in)
                .dismissAnim(bas_out);

        sDialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                dismissAllDialog();
                showNoPermissionDialog(activity);
            }
        },
                onBtnClickLRequestPermissions
        );

        sDialog.show();
    }

    public static void showRequestPrivatePermissionsDialog(final Activity activity, OnBtnClickL onBtnClickLRequestPermissions) {
        if (activity == null) {
            return;
        }
        BaseAnimatorSet bas_in = new FadeEnter();
        BaseAnimatorSet bas_out = new FadeExit();

        String title = "\t\"" + activity.getString(R.string.app_name) + "\"想获取您的隐私信息:";
        String content = "\"隐私\"包括地理位置或摄像头或相册等。这些可在\"设置\"中配置。";

        if (sDialog != null && sDialog.isShowing()) {
            return;
        }

        sDialog = new NormalDialog(activity);

        sDialog.isTitleShow(true)
                .title(title)
                .titleTextColor(Color.parseColor("#000000"))
                .titleTextSize(16)
                .btnNum(2)
                .style(NormalDialog.STYLE_TWO)
                .cornerRadius(5)
                .content(content)
                .contentGravity(Gravity.CENTER)
                .contentTextSize(13)
                .contentTextColor(Color.parseColor("#333333"))
                .dividerColor(Color.parseColor("#CCCCCC"))
                .btnText("不允许", "允许")
                .btnTextSize(15.5f, 15.5f)
                .btnTextColor(Color.parseColor("#333333"), Color.parseColor("#41ACFD"))
                .widthScale(0.8f)
                .showAnim(bas_in)
                .dismissAnim(bas_out);

        sDialog.setOnBtnClickL(new OnBtnClickL() {
                                   @Override
                                   public void onBtnClick() {
                                       dismissAllDialog();
                                       showNoPermissionDialog(activity);
                                   }
                               },
                onBtnClickLRequestPermissions
        );

        sDialog.show();
    }

    public static void showNoPermissionDialog(Activity activity,String content) {
        final NormalDialog dialog = new NormalDialog(activity);

        dialog.isTitleShow(false)
                .btnNum(1)
                .bgColor(Color.parseColor("#FFFFFF"))
                .cornerRadius(5)
                .content(content)
                .contentGravity(Gravity.CENTER)
                .contentTextSize(13)
                .contentTextColor(Color.parseColor("#333333"))
                .dividerColor(Color.parseColor("#CCCCCC"))
                .btnText("确定")
                .btnTextSize(15.5f)
                .btnTextColor(Color.parseColor("#0092FF"))
                .widthScale(0.7f)
                .show();

        dialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                dialog.dismiss();
            }
        });
    }

    public static void showNoPermissionDialog(final Activity activity) {
        if (activity == null) {
            return;
        }
        BaseAnimatorSet bas_in = new FadeEnter();
        BaseAnimatorSet bas_out = new FadeExit();

        String strNoPermission = activity.getString(R.string.error_no_permission);
        String strBtnOk = activity.getString(R.string.btn_ok);

        if (sDialog != null && sDialog.isShowing()) {
            return;
        }

        sDialog = new NormalDialog(activity);

        sDialog.isTitleShow(false)
                .btnNum(1)
                .bgColor(Color.parseColor("#FFFFFF"))
                .cornerRadius(5)
                .content(strNoPermission)
                .contentGravity(Gravity.CENTER)
                .contentTextSize(13)
                .contentTextColor(Color.parseColor("#333333"))
                .dividerColor(Color.parseColor("#CCCCCC"))
                .btnText(strBtnOk)
                .btnTextSize(15.5f, 15.5f)
                .btnTextColor(Color.parseColor("#0092FF"))
                .widthScale(0.7f)
                .showAnim(bas_in)
                .dismissAnim(bas_out)
                .show();

        sDialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                dismissAllDialog();
                activity.finish();
                ApplicationHelper.getInstance().exit();
            }
        });

        sDialog.show();
    }

    public static void showNoInternetDialog(final Activity activity) {
        if (activity == null) {
            return;
        }

        String strNoPermission = activity.getString(R.string.error_no_internet);
        String strBtnOk = activity.getString(R.string.btn_ok);

        if (sDialog != null && sDialog.isShowing()) {
            return;
        }

        sDialog = new NormalDialog(activity);

        sDialog.isTitleShow(false)
                .btnNum(1)
                .bgColor(Color.parseColor("#FFFFFF"))
                .cornerRadius(5)
                .content(strNoPermission)
                .contentGravity(Gravity.CENTER)
                .contentTextSize(13)
                .contentTextColor(Color.parseColor("#333333"))
                .dividerColor(Color.parseColor("#CCCCCC"))
                .btnText(strBtnOk)
                .btnTextSize(15.5f, 15.5f)
                .btnTextColor(Color.parseColor("#0092FF"))
                .widthScale(0.7f)
                .show();

        sDialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                activity.finish();
                ApplicationHelper.getInstance().exit();
            }
        });

        sDialog.show();
    }

    private static void dismissCustomDialog() {
        if (sDialog != null) {
            sDialog.superDismiss();
            sDialog = null;
        }
    }

    public static void dismissAllDialog() {
        dismissCustomDialog();

        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }
}
